from zipline.api import order, record, symbol, set_commission, order_target
from zipline.finance.commission import PerTrade

def initialize(context):
    # 设置参数
    context.period = 20  # 通道计算周期
    context.asset = symbol('AAPL')  # 示例标的，实际使用时可根据需要修改
    # 设置交易佣金
    set_commission(PerTrade(cost=1.0))

def handle_data(context, data):
    # 获取历史高价和低价
    high_prices = data.history(context.asset, 'high', context.period, '1d')
    low_prices = data.history(context.asset, 'low', context.period, '1d')
    
    # 计算通道上下轨
    high_channel = high_prices.max()
    low_channel = low_prices.min()
    
    # 获取当前收盘价
    current_close = data.current(context.asset, 'close')
    
    # 交易逻辑
    if not context.portfolio.positions[context.asset]:  # 没有持仓
        if current_close > high_channel:  # 突破上轨
            order(context.asset, 100)  # 买入100股
    else:  # 有持仓
        if current_close < low_channel:  # 跌破下轨
            order_target(context.asset, 0)  # 平仓
    
    # 记录数据（可选）
    record(high_channel=high_channel, low_channel=low_channel, close=current_close)